<template>
	<div>
		<div class="toolbar mt-2">
			<a-form ref="searchRef" :model="searchState" :label-col="{style: { width: '80px' }}" @finish="current=1">
				<a-row :gutter="20">
					<a-col :md="12" :lg="8" :xl="6">
						<a-form-item label="名称" class="mb-0">
							<a-input v-model:value="searchState['name']" placeholder="请输入" allow-clear></a-input>
						</a-form-item>
					</a-col>
					<a-col :md="12" :lg="8" :xl="6">
						<a-space>
							<a-button type="primary" html-type="submit">
								<search-outlined />搜索
							</a-button>

							<a-button type="primary" @click="addModule">
								<plus-outlined />添加
							</a-button>
						</a-space>
					</a-col>
				</a-row>
			</a-form>
		</div>

		<div class="container mt-2">
			<a-table :columns="columns" :scroll="tableScroll" :expanded-row-keys="expandedRowKeys" row-key="id" :data-source="moduleSource" :pagination="pagination" :loading="loading" :row-selection="rowSelection" @change="(pag) => current = pag.current" @expanded-rows-change="expandedRowsChange ">
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'operation'">
						<a-space>
							<a-button type="link" @click="editModule(record)">
								<edit-outlined />修改
							</a-button>

							<a-popconfirm title="确定要删除选中的记录吗？" ok-text="是" cancel-text="否" @confirm="deleteModule(record.id)">
								<a-button type="link" style="color:#ff7875">
									<delete-outlined />删除
								</a-button>
							</a-popconfirm>
						</a-space>
					</template>

					<template v-else-if="column.key === 'nodes'">
						<ol>
							<li v-for="item in record.nodes" :key="item.id">
								<dl>
									<dt>{{ item.name }}</dt>
									<dd>
										<a-tag v-for="role in item.roles" :key="role.id">{{ role.name }}</a-tag>
									</dd>
								</dl>
							</li>
						</ol>
					</template>
				</template>
			</a-table>

			<a-modal v-model:visible="visible" :width="640" :title="`${formState.id ? '修改' : '添加'}审批流`" @ok="saveModule">
				<a-form ref="formRef" :model="formState" v-bind="{labelCol:{style:{width:'100px'}},wrapperCol:{span:18}}">
					<a-form-item label="名称" name="name" :rules="{required:true, message:'请输入名称'}">
						<a-input v-model:value="formState.name" />
					</a-form-item>
					<a-form-item label="模块名" name="module" :rules="{required:true, message:'请输入模块名'}">
						<a-input v-model:value="formState.module" />
					</a-form-item>
					<a-form-item label="模块表名" name="table" :rules="{required:true, message:'请输入模块表名'}">
						<a-input v-model:value="formState.table" />
					</a-form-item>
					<a-form-item label="模块表主键" name="table_pk">
						<a-input v-model:value="formState.table_pk" placeholder="id" />
					</a-form-item>
					<a-form-item label="模块表字段" name="table_field">
						<a-input v-model:value="formState.table_field" placeholder="workflow_status" />
					</a-form-item>
					<!--
					<a-form-item label="路由名称" name="route_name">
						<a-input v-model:value="formState.route_name" />
					</a-form-item>
					-->
					<a-form-item label="路由路径" name="route_path">
						<a-input v-model:value="formState.route_path" />
					</a-form-item>

					<a-form-item label="状态" name="status">
						<a-radio-group v-model:value="formState.status">
							<a-radio :value="1">启用</a-radio>
							<a-radio :value="0">停用</a-radio>
						</a-radio-group>
					</a-form-item>

					<div v-for="(item, key) in formState.nodes" :key="key">
						<a-form-item>
							<template #label>
								<div>
									节点【{{ key + 1 }}】
									<div v-if="formState.nodes.length > 1" class="btn">
										<a-button size="small" @click="removeNode(key)">删除</a-button>
									</div>
								</div>
							</template>

							<a-form-item label="名称" :name="['nodes', key, 'name']" :label-col="{style:{width:'80px'}}" :rules="{required:true, message:'请输入节点名称'}">
								<a-input v-model:value="item.name" />
							</a-form-item>
							<a-form-item label="达标人数" :name="['nodes', key, 'lowest']" :label-col="{style:{width:'80px'}}" :rules="{required:true, message:'请输入达标人数'}">
								<a-input-number v-model:value="item.lowest" :min="1" />
							</a-form-item>
							<a-form-item label="审核角色" :name="['nodes', key, 'role_ids']" :label-col="{style:{width:'80px'}}" :rules="{required:true, message:'请选择审核角色'}">
								<a-select v-model:value="item.role_ids" mode="multiple" :options="roleSource" option-filter-prop="label"></a-select>
							</a-form-item>
						</a-form-item>
					</div>
					<div class="text-center">
						<a-button @click="addNode">新增审批节点</a-button>
					</div>
				</a-form>
			</a-modal>
		</div>
	</div>
</template>

<script setup lang="jsx">
import dayjs from 'dayjs';
import { ref, computed, getCurrentInstance } from "vue";
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons-vue";

const searchRef = ref();
const searchState = ref({});

const columns = [
	{
		title: "ID",
		dataIndex: "id",
		width: 60,
		fixed: "left"
	},
	{
		title: "名称",
		dataIndex: "name",
		width: 200,
		fixed: "left"
	},
	{
		title: "模块",
		dataIndex: "module",
		width: 160
	},
	{
		title: "状态",
		dataIndex: "status",
		width: 100,
		align: 'center',
		customRender: ({ text, record, index, column }) => {
			return text === 1 ? <a-tag color="green">启用</a-tag> : <a-tag>停用</a-tag>;
		}
	},
	{
		title: "审批流",
		key: "nodes",
		width: 300
	},
	{
		title: "创建时间",
		dataIndex: "create_time",
		width: 180,
		align: 'center',
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format('YYYY-MM-DD HH:mm:ss')
		}
	},
	{},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 160,
		align: "center"
	}
];

const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 250
}));

const expandedRowKeys = ref([]);
const expandedRowsChange = e => {
	expandedRowKeys.value = e;
};
const rowSelection = ref();

import { post } from "../utils";
import { usePagination } from "vue-request";
const { data, loading, run, current, pageSize, total } = usePagination(params => post("workflow/module", { ...params, ...searchState.value }), {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});
const moduleSource = computed(
	() =>
		data.value?.data.map(d => {
			d.nodes = d.nodes.map(n => {
				n.role_ids = n.roles.map(r => r.id);
				return n;
			});
			return d;
		}) || []
);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const roleSource = ref([]);
post("workflow/role").then(data => {
	roleSource.value = data;
});

const visible = ref(false);
const formRef = ref();
const formState = ref({});

const addModule = () => {
	formState.value = {
		status: 1,
		nodes: []
	};
	visible.value = true;
};

const editModule = data => {
	formState.value = { ...data };
	visible.value = true;
};

const deleteModule = id => {
	post("workflow/module/delete", { id }).then(() => {
		proxy.$message.success("审批模块删除成功");
		current.value = moduleSource.value.length === 1 ? Math.max(current.value - 1, 1) : current.value;
	});
};

const { proxy } = getCurrentInstance();
const saveModule = () => {
	formRef.value
		.validate()
		.then(() => {
			const params = { ...formState.value };

			if (!params.nodes.length) {
				proxy.$message.error("请设置审批节点");
				return;
			}
			params.nodes = JSON.stringify(params.nodes);

			post("workflow/module/save", params).then(() => {
				proxy.$message.success("审批模块保存成功");
				visible.value = false;
				current.value = !params.id && moduleSource.value.length === pageSize.value ? Math.max(current.value + 1, 1) : current.value;
			});
		})
		.catch(() => {});
};

const addNode = () => {
	formState.value.nodes.push({});
};

const removeNode = index => {
	formState.value.nodes.splice(index, 1);
};
</script>

<style scoped lang="scss">
.toolbar,
.container {
	padding: 12px;
	background: #fff;
}

.text-center {
	text-align: center;
}

.ant-form-item-label {
	.btn {
		text-align: center;
		margin-top: 10px;
	}
}

.ant-table-cell {
	ol {
		padding-left: 16px;
	}
	dt {
		margin-bottom: 5px;
	}
	.ant-tag {
		margin: 0 8px 8px 0 !important;

		& + .ant-tag {
			margin: 0;
		}
	}
}
</style>
